package com.meitianhui.convenitenbuy.module.store.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.module.store.contract.PreferentialDetailContract;
import com.meitianhui.convenitenbuy.module.store.di.DaggerStoreComponent;
import com.meitianhui.convenitenbuy.module.store.di.StoreModule;
import com.meitianhui.convenitenbuy.module.store.model.CouponCardInfo;
import com.meitianhui.convenitenbuy.module.store.presenter.PreferentialDetailPresenter;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.util.GlideUtils;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.ReceiveSuccessDialog;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.meitianhui.convenitenbuy.Constants.BANNER_TIME;
import static com.meitianhui.convenitenbuy.R.id.view_bg;

/**
 * Created by Administrator on 2017/11/29.
 */

public class PreferentialDetailActivity extends BaseToolbarActivity implements PreferentialDetailContract.View {
    private Banner mBanner;
    private TextView mTvLeft;
    private TextView mTvCondition;
    private TextView mTvContent;
    private TextView mTvType;
    private TextView mTvTitle;
    private TextView mTvEndTime;
    private TextView mTvLeft1, mTvLeft2;
    private TextView mTvName, mTvName2, mTvAddress;
    private LinearLayout mLlLeft;
    private CouponCardInfo.Coupon mCoupon;
    private View mViewBg;//
    private String mStoreId, mStoreName, mStoreAddress;
    private String mCategoryId;
    private ReceiveSuccessDialog mDialog;
    @Inject
    PreferentialDetailPresenter presenter;

    @Override
    protected int setView() {
        return R.layout.activity_preferential_detail;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerStoreComponent
                .builder()
                .appComponent(App.getInstance().getAppComponent())
                .storeModule(new StoreModule(this))
                .build()
                .inject(this);
        setTbTitle("优惠详情");
        isEnable(false);
        initView();
        initData();
    }


    private void initView() {
        mViewBg = getViewById(view_bg);
        mViewBg.getBackground().setAlpha(80);
        mTvName = getViewById(R.id.tv_name);
        mTvName2 = getViewById(R.id.tv_name2);
        mTvAddress = getViewById(R.id.tv_address);
        mBanner = getViewById(R.id.banner);
        mTvLeft = getViewById(R.id.tv_left);
        mTvEndTime = getViewById(R.id.tv_end_time);
        mTvCondition = getViewById(R.id.tv_condition);
        mTvContent = getViewById(R.id.tv_content);
        mTvType = getViewById(R.id.tv_type);
        RxUtils.bindEvents(mTvType, this);
        mLlLeft = getViewById(R.id.ll_left);
        mTvTitle = getViewById(R.id.tv_title);
        mTvLeft1 = getViewById(R.id.tv_left1);
        mTvLeft2 = getViewById(R.id.tv_left2);
        initIntent();
    }


    private void initIntent() {
        Intent intent = this.getIntent();
        mCoupon = (CouponCardInfo.Coupon) intent.getSerializableExtra("coupon");
        mStoreId = intent.getStringExtra("store_id");
        mStoreName = intent.getStringExtra("store_name");
        mStoreAddress = intent.getStringExtra("store_address");
        presenter.getCouponDetail(mCoupon.getItem_id());
        pushPayResult();
    }


    private void initData() {
        mCategoryId = mCoupon.getCategory_id();
        mTvName.setText(mStoreName);
        mTvName2.setText(mStoreName);
        mTvAddress.setText(mStoreAddress);
        String limitAmount = mCoupon.getLimit_amount();
        mTvCondition.setText("需消费" + (TextUtils.isEmpty(limitAmount) ? "" : limitAmount) + "元可用");
        mTvContent.setText(mCoupon.getCoupon_desc());//优惠内容
        Integer num = Integer.parseInt(mCoupon.getUsable_num());//剩余数量
        if (Constants.CONS_CASH.equals(mCategoryId)) {//现金购买
            mTvType.setText("现金购买");
            mLlLeft.setVisibility(View.VISIBLE);
            mTvTitle.setText(mCoupon.getTitle());
            mTvLeft2.setText(mCoupon.getMarket_price());
        } else if (Constants.CONS_LIQUAN.equals(mCategoryId)) {//礼券兑换
            mTvType.setText("礼券兑换");
            mLlLeft.setVisibility(View.VISIBLE);
            mTvLeft1.setText(mCoupon.getMarket_price_voucher());
            mTvLeft2.setText("礼券");
        } else if (Constants.CONS_FREE.equals(mCategoryId)) {//免费领取
            mTvType.setText("免费领取");
            mLlLeft.setVisibility(View.GONE);
        }
//        if (num <= 0) {//已领光
//            TipUtils.showToast(App.getInstance(),"该优惠券已领光",3);
//            finish();
//            return;
//        }
        mTvLeft.setText("剩" + num + "份");
        mTvLeft.setTag(num + "");
        mTvEndTime.setText(mCoupon.getExpired_date().substring(0, 10));
    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.tv_type:   //领取
                if (!InfoProvider.getLoginStatus(this)) {
                    JumpUtil.jumpToLoginActivity(0, PreferentialDetailActivity.this, 0, "");
                    return;
                }
                if (Constants.CONS_CASH.equals(mCategoryId)) {//现金购买
                    if (TextUtils.isEmpty(mTvLeft2.getText().toString())) {
                        TipUtils.showToast(App.getInstance(), "请稍后，没有请求到数据");
                    }
                    Intent intent = new Intent(PreferentialDetailActivity.this, CouponPayActivity.class);
                    intent.putExtra("coupon", mCoupon);
                    intent.putExtra("store_id", mStoreId);
                    intent.putExtra("store_name", mStoreName);
                    startActivity(intent);
                } else if (Constants.CONS_LIQUAN.equals(mCategoryId)) {//礼券兑换
                    Integer num = Integer.parseInt(mTvLeft.getTag().toString());
                    if (num <= 0) {
                        TipUtils.showToast(App.getInstance(), "礼券已领光", 3);
                        return;
                    }
                    Intent intent2 = new Intent(PreferentialDetailActivity.this, CouponPayActivity.class);
                    intent2.putExtra("coupon", mCoupon);
                    intent2.putExtra("store_id", mStoreId);
                    intent2.putExtra("store_name", mStoreName);
                    startActivityForResult(intent2, 1001);
                } else if (Constants.CONS_FREE.equals(mCategoryId)) {//免费领取
                    Integer num = Integer.parseInt(mTvLeft.getTag().toString());
                    if (num <= 0) {
                        TipUtils.showToast(App.getInstance(), "礼券已领光", 3);
                        return;
                    }
                    presenter.receiveCoupon(mCoupon.getItem_id());
                }

                break;

        }
    }

    @Override
    public void getCouponDetailSuccess(CouponCardInfo cardInfo) {
        if (cardInfo.detail.size() > 0) {
            List<String> urlList = new ArrayList<>();
            mCoupon = cardInfo.detail.get(0);
            initData();
            if (mCoupon.getPic_path() != null) {
                String picPath = mCoupon.getPic_path();
                String[] urlStr = picPath.split(",");
                for (int i = 0; i < urlStr.length; i++) {
                    String url = cardInfo.getDoc_url().get(urlStr[i]);
                    urlList.add(url);
                }
            }
            mBanner.setImages(urlList)
                    .setDelayTime(BANNER_TIME)   //设置轮播时间
                    .setImageLoader(new GlideImageLoader())
                    .start();

        }
    }

    @Override
    public void receiveCouponSuccess() {
        mDialog = new ReceiveSuccessDialog(PreferentialDetailActivity.this, R.style.dialog_with_alpha, "恭喜你领取成功");
        mDialog.show();
        mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                RxBus.get().post(new PayResultBean(Constants.PAY_RESULT_SUCCESS));
                finish();
            }
        });
    }

    @Override
    public void onFail(int code, String msg) {
        TipUtils.showToast(App.getInstance(), "领取失败" + msg, 2);
    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            GlideUtils.setRectImage(PreferentialDetailActivity.this,(String) path, R.mipmap.icon_default_picture, R.mipmap.icon_default_picture, imageView);
        }
    }

    private void pushPayResult() {
        Disposable disposable = RxBus.get().toFlowable(PayResultBean.class).subscribe(new Consumer<PayResultBean>() {
            @Override
            public void accept(PayResultBean payResultBean) throws Exception {
                if (payResultBean != null) {
                    if (payResultBean.result == Constants.PAY_RESULT_SUCCESS) {
                        presenter.getCouponDetail(mCoupon.getItem_id());
                    }
                }
            }
        });
        mCompositeDisposable.add(disposable);
    }

    @Override
    protected void onRefreshData() {

    }

    @Override
    public void showError(String msg) {

    }

}
